package com.mamesoft.namibiamc.ws;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class WSClient extends JPanel implements ActionListener {

    Socket s;
    private static String SERVER = "localhost";
    private static int PORT = 8084;
    private static String PATH = "/NamibiaMedicalControl/ws/sms/";
    private String[] rubrica = {"Tom Riddle: 0471202939","Pasquale Marino: 0471568512", "Rinaldo Gentili: 3401669315", "Stefano Valente: 3401669315", "Valeria Mazza: 3401669315", "Isacco Galli: 0471502010", "Sconosciuto: 0417401706"};
    JTextArea message, response;
    JComboBox numeri;
    JLabel n;

    WSClient() {

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception ex) {
        }
        this.setLayout(new GridLayout(1, 2));

        JPanel send = new JPanel();
        send.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        send.setLayout(new GridLayout(3, 1));
        JPanel recive = new JPanel();
        recive.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        recive.setLayout(new BorderLayout());

        this.add(send);
        this.add(recive);

        JPanel mex = new JPanel();
        mex.setLayout(new BorderLayout());
        JLabel m = new JLabel("Messaggio");
        m.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
        mex.add(m, BorderLayout.NORTH);
        message = new JTextArea();
        message.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        mex.add(message, BorderLayout.CENTER);
        send.add(mex);


        JPanel contatti = new JPanel();
        contatti.setLayout(new BorderLayout());

        JLabel c = new JLabel("Contatto");
        c.setBorder(BorderFactory.createEmptyBorder(10, 5, 5, 5));
        contatti.add(c, BorderLayout.NORTH);
        numeri = new JComboBox(rubrica);
        n = new JLabel("  ");
        n.setBorder(BorderFactory.createEmptyBorder(20, 5, 0, 5));
        contatti.add(n, BorderLayout.SOUTH);
        contatti.add(numeri, BorderLayout.CENTER);
        send.add(contatti);

        JPanel i = new JPanel();
        i.setBorder(BorderFactory.createEmptyBorder(45, 5, 5, 5));
        JButton invia = new JButton("Invia");
        invia.addActionListener(this);
        i.add(invia);
        send.add(i);


        JLabel risposta = new JLabel("Risposta");
        risposta.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
        recive.add(risposta, BorderLayout.NORTH);
        response = new JTextArea();
        JScrollPane scroll = new JScrollPane(response, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        response.setEditable(false);

        recive.add(scroll, BorderLayout.CENTER);

        this.validate();
    }

    private String getXml(String phone, String message) {
        String infoXml = "";
        try {
            s = new Socket();
            s.connect(new InetSocketAddress(SERVER, PORT));

            BufferedReader s_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            PrintWriter s_out = new PrintWriter(s.getOutputStream(), true /* autoFlush */);
            n.setText(PATH + phone + "?text=" + message);

            s_out.println("GET " + PATH + phone + "?text=" + message + " HTTP/1.0");
            s_out.println("Host: " + SERVER);
            s_out.println();

            String data = null;

            while ((data = s_in.readLine()) != null) {
                infoXml += data;
            }

            infoXml = infoXml.substring(infoXml.indexOf('<'));

        } catch (IOException ex) {
            System.err.println("IO:" + ex.getMessage());
            infoXml = "";
        }
        return infoXml;
    }

    public static void main(String args[]) {
        JFrame f = new JFrame();
        f.setTitle("Client");
        f.setVisible(true);
        f.setSize(600, 300);
        f.setLocation(200, 100);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new WSClient());
        f.setResizable(false);
        f.validate();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            int i = numeri.getSelectedIndex();
            String nTelefono = rubrica[i].substring(rubrica[i].indexOf(':') + 2);

            String messaggio = "";

            String xml = getXml(nTelefono, message.getText());

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader reader = new StringReader(xml);
            InputSource is = new InputSource(reader);
            Document doc = db.parse(is);
            Element rootElement = doc.getDocumentElement();
            rootElement.normalize();
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression exp = xpath.compile("/visite/num-visite");
            NodeList nodes = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);

            if (nodes.item(0) != null) {
                String nV = nodes.item(0).getTextContent();
                int nVisite = Integer.parseInt(nV);
                if (nVisite != 0) {
                    exp = xpath.compile("/visite/visita/username");
                    NodeList user = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
                    exp = xpath.compile("/visite/visita/data-visita");
                    NodeList data = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
                    exp = xpath.compile("/visite/visita/tipo-visita");
                    NodeList tipo = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
                    exp = xpath.compile("/visite/visita/descrizione");
                    NodeList descrizione = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);

                    for (int j = 0; j < user.getLength(); j++) {
                        messaggio += "Visita: " + (j+1) +"\n";
                        messaggio += "Utente: " + user.item(j).getTextContent() + "\n";
                        messaggio += "Data: " + data.item(j).getTextContent() + "\n";
                        messaggio += "Tipo: " + tipo.item(j).getTextContent() + "\n";
                        messaggio += "Descrizione: " + descrizione.item(j).getTextContent() + "\n\n";
                    }
                }else{
                    messaggio += "Non ci sono visite \nassociate a questo numero.";
                }
            }

            response.setText(messaggio);

        } catch (Exception ex) {
            ex.printStackTrace();
            response.setText("");
        }
    }
}
